/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.zhpan.bannerview.utils;

/**
 * ArgbEvaluator
 *
 * @since 2021-03-24
 */
public class ArgbEvaluator {

    /**
     * shapeElement.setRgbColor(new RgbColor(new RgbColor((Integer) AttrUtil.evaluate(ratio, Color.GREEN.getValue(), Color.BLACK.getValue())).asArgbInt()));
     * setBackground(shapeElement);
     * @param fraction 參數
     * @param startValue 參數
     * @param endValue 參數
     * @return Object
     */
    public static Object evaluate(float fraction, int startValue, int endValue) {
        int startInt = (Integer) startValue;

        float startA = ((startInt >> 24) & 0xff) / 255.0f;
        float startR = ((startInt >> 16) & 0xff) / 255.0f;
        float startG = ((startInt >>  8) & 0xff) / 255.0f;
        float startB = ( startInt        & 0xff) / 255.0f;

        int endInt = (Integer) endValue;

        float endA = ((endInt >> 24) & 0xff) / 255.0f;
        float endR = ((endInt >> 16) & 0xff) / 255.0f;
        float endG = ((endInt >>  8) & 0xff) / 255.0f;
        float endB = ( endInt        & 0xff) / 255.0f;

        // convert from sRGB to linear
        startR = (float) Math.pow(startR, 2.2);
        startG = (float) Math.pow(startG, 2.2);
        startB = (float) Math.pow(startB, 2.2);

        endR = (float) Math.pow(endR, 2.2);
        endG = (float) Math.pow(endG, 2.2);
        endB = (float) Math.pow(endB, 2.2);

        // compute the interpolated color in linear space
        float a1 = startA + fraction * (endA - startA);
        float r1 = startR + fraction * (endR - startR);
        float g1 = startG + fraction * (endG - startG);
        float b1= startB + fraction * (endB - startB);

        // convert back to sRGB in the [0..255] range
        a1 = a1 * 255.0f;
        r1 = (float) Math.pow(r1, 1.0 / 2.2) * 255.0f;
        g1 = (float) Math.pow(g1, 1.0 / 2.2) * 255.0f;
        b1 = (float) Math.pow(b1, 1.0 / 2.2) * 255.0f;

        return Math.round(a1) << 24 | Math.round(r1) << 16 | Math.round(g1) << 8 | Math.round(b1);
    }

}
